package com.example.yorkfeng.musicdemo;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yorkfeng on 16/8/3.
 */
public class MusicService extends Service {

    private static final int updateProgress = 1;
    private static final int updateDuration = 2;
    private static final int updateInfo = 3;
    private static final int updateList = 4;

    public static final int ALL_LOOP = 0;
    public static final int SINGLE_LOOP = 1;
    public static final int RAND_LOOP = 2;
    private int loopMode = ALL_LOOP;

    //广播
    public static final String ACTION_UPDATE_PROGRESS = "com.example.nature.UPDATE_PROGRESS";
    public static final String ACTION_UPDATE_DURATION = "com.example.nature.UPDATE_DURATION";
    public static final String ACTION_UPDATE_INFO = "com.example.nature.UPDATE_INFO";
    public static final String ACTION_UPDATE_LIST = "com.example.nature.UPDATE_LIST";

    String[] mCursorCols = new String[] {
            "audio._id AS _id", // index must match IDCOLIDX below
            MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ALBUM_ID,
            MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION
    };
    private MediaPlayer mMediaPlayer;
    private Cursor mCursor;
    private int mPlayPosition = 0;
    private boolean flagPro = false, flagStop = false;
    private static List<MusicInfo> musicList = new ArrayList<MusicInfo>();

    //控制
    public static final String INIT_ACTION = "com.example.yorkfeng.musicdemo.INIT_ACTION";
    public static final String PLAY_ACTION = "com.example.yorkfeng.musicdemo.PLAY_ACTION";
    public static final String PAUSE_ACTION = "com.example.yorkfeng.musicdemo.PAUSE_ACTION";
    public static final String NEXT_ACTION = "com.example.yorkfeng.musicdemo.NEXT_ACTION";
    public static final String PREVIOUS_ACTION = "com.example.yorkfeng.musicdemo.PREVIOUS_ACTION";
    public static final String SEEK_ACTION = "com.example.yorkfeng.musicdemo.SEEK_ACTION";
    public static final String CLOSE_ACTION = "com.example.yorkfeng.musicdemo.CLOSE_ACTION";
    public static final String UPDATE_ACTION = "com.example.yorkfeng.musicdemo.UPDATE_ACTION";
    public static final String CHANGE_ACTION = "com.example.yorkfeng.musicdemo.CHANGE_ACTION";
    public static final String MODE_ACTION = "com.example.yorkfeng.musicdemo.MODE_ACTION";
    public static final String LIST_ACTION = "com.example.yorkfeng.musicdemo.LIST_ACTION";

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("MusicServer onCreate");
        mMediaPlayer = new MediaPlayer();
        //通过一个URI可以获取所有音频文件
        Uri MUSIC_URL = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        //播放不到一秒钟，我这里作了处理，默认大于10秒的可以看作是歌
        mCursor = getContentResolver().query(MUSIC_URL, mCursorCols, "duration > 10000", null, null);

        if(mCursor == null){

        }else if(!mCursor.moveToFirst()){

        }else{
            int displayNameCol = mCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int albumCol = mCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
            int idCol = mCursor.getColumnIndex(MediaStore.Audio.Media._ID);
            int durationCol = mCursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
            int sizeCol = mCursor.getColumnIndex(MediaStore.Audio.Media.SIZE);
            int artistCol = mCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
            int urlCol = mCursor.getColumnIndex(MediaStore.Audio.Media.DATA);

            do{
                String title = mCursor.getString(displayNameCol);
                String album = mCursor.getString(albumCol);
                long id = mCursor.getLong(idCol);
                int duration = mCursor.getInt(durationCol);
//                long size = mCursor.getLong(sizeCol);
                String artist = mCursor.getString(artistCol);
                String url = mCursor.getString(urlCol);

                MusicInfo musicInfo = new MusicInfo(id, title);
                musicInfo.setAlbum(album);
                musicInfo.setDuration(duration);
//                musicInfo.setSize(size);
                musicInfo.setArtist(artist);
                musicInfo.setUrl(url);
                musicList.add(musicInfo);

            }while(mCursor.moveToNext());
        }

        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                next();
            }
        });
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

        String action = intent.getAction();
        if(action.equals(PLAY_ACTION)){
            play();

        }else if(action.equals(PAUSE_ACTION)){
            pause();

        }else if(action.equals(CLOSE_ACTION)){
            close();

        }else if(action.equals(NEXT_ACTION)){
            next();

        }else if(action.equals(PREVIOUS_ACTION)){
            previous();

        }else if(action.equals(SEEK_ACTION)){
            int postion = intent.getIntExtra("position", 0);
            seek(postion);

        }else if(action.equals(UPDATE_ACTION)){
            handler.sendEmptyMessage(updateDuration);
            handler.sendEmptyMessage(updateInfo);

        }else if(action.equals(INIT_ACTION)){
            int postion = intent.getIntExtra("position", 0);
            mPlayPosition = postion;
            inite();
        }else if(action.equals(CHANGE_ACTION)){
            int postion = intent.getIntExtra("position", 0);
            mPlayPosition = postion;
            inite();
            mMediaPlayer.start();
        }else if(action.equals(MODE_ACTION)){
            int tmp = intent.getIntExtra("mode", 0);
            loopMode = tmp;
        }else if(action.equals(LIST_ACTION)){
            handler.sendEmptyMessage(updateList);
        }
    }

    public static List<MusicInfo> getMusicList(){
        return musicList;
    }

    //play the music
    public void play() {
        if (!flagPro) {
            handler.sendEmptyMessage(updateProgress);
            flagPro = true;
        }
        mMediaPlayer.start();
    }

    //play the music
    public void pause() {
        mMediaPlayer.pause();
        flagPro = false;
    }

    //关闭时，结束服务
    public void close() {
        flagPro = false;
        flagStop = true;
        stopSelf();
    }
    //上一首
    public void previous() {
        switch (loopMode) {
            case ALL_LOOP:
                if (mPlayPosition == 0) {
                    mPlayPosition = mCursor.getCount() - 1;
                } else {
                    mPlayPosition--;
                }
                inite();
                mMediaPlayer.start();
                break;

            case SINGLE_LOOP:
                inite();
                mMediaPlayer.start();
                break;

            case RAND_LOOP:
                mPlayPosition = randPosition();
                inite();
                mMediaPlayer.start();
                break;

            default:
                break;
        }
    }
    public void next() {
        switch (loopMode) {
            case ALL_LOOP:
                if (mPlayPosition == mCursor.getCount() - 1) {
                    mPlayPosition = 0;
                } else {
                    mPlayPosition++;
                }
                inite();
                mMediaPlayer.start();
                break;

            case SINGLE_LOOP:
                inite();
                mMediaPlayer.start();
                break;

            case RAND_LOOP:
                mPlayPosition = randPosition();
                inite();
                mMediaPlayer.start();
                break;

            default:
                break;
        }
    }
    public void seek(int position) {
        mMediaPlayer.seekTo(position * 1000);
    }
    public void inite() {
        mMediaPlayer.reset();
        String dataSource = getDateByPosition(mCursor, mPlayPosition);

        SharedPreferences.Editor mEditor = MainActivity.mSharePre.edit();
        mEditor.putInt("mMusicPlayPosition", mPlayPosition);
        mEditor.commit();

        try {
            mMediaPlayer.setDataSource(dataSource);
            mMediaPlayer.prepare();
            if (!flagPro) {
                handler.sendEmptyMessage(updateProgress);
                flagPro = true;
            }
            handler.sendEmptyMessage(updateDuration);
            handler.sendEmptyMessage(updateInfo);
        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    //根据位置来获取歌曲位置
    public String getDateByPosition(Cursor c,int position){
        c.moveToPosition(position);
        int dataColumn = c.getColumnIndex(MediaStore.Audio.Media.DATA);
        String data = c.getString(dataColumn);
        return data;
    }
    //获取当前播放歌曲名
    public String getTitleByPosition(Cursor c,int position){
        c.moveToPosition(position);
        int artistColumn = c.getColumnIndex(MediaStore.Audio.Media.TITLE);
        String info = c.getString(artistColumn);
        return info;

    }
    //获取当前播放歌曲演唱者及专辑名
    public String getInfoByPosition(Cursor c,int position){
        c.moveToPosition(position);
        int artistColumn = c.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        int album = c.getColumnIndex(MediaStore.Audio.Media.ALBUM);
        String info = c.getString(artistColumn)+" - " + c.getString(album);
        return info;

    }
    //获取当前播放歌曲长度
    public String getDuration(Cursor c,int position) {
        c.moveToPosition(position);
        int DURATION = c.getColumnIndex(MediaStore.Audio.Media.DURATION);
        return c.getString(DURATION);
    }
    //获取当前播放歌曲专辑封面
    public String getAlbumIcon(Cursor c,int position) {
        c.moveToPosition(position);
        int ALBUM_ID = c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
        return getAlbumArt(ALBUM_ID);
    }

    private String getAlbumArt(int album_id) {
        String mUriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[] { "album_art" };
        Cursor cur = this.getContentResolver().query(
                Uri.parse(mUriAlbums + "/" + Integer.toString(album_id)),
                projection, null, null, null);
        String album_art = null;
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        cur.close();
        cur = null;

        return album_art;
    }

    //获取当前播放歌曲演唱者及专辑名,专辑封面
    private void toUpdateList(){
        Intent intent = new Intent();
        intent.setAction(ACTION_UPDATE_LIST);
        intent.putExtra(ACTION_UPDATE_LIST, (Serializable) musicList);
        sendBroadcast(intent);
    }

    //获取当前播放歌曲演唱者及专辑名,专辑封面
    private void toUpdateInfo(){
        String info = getInfoByPosition(mCursor, mPlayPosition);
        String title = getTitleByPosition(mCursor, mPlayPosition);
        String albumArt = getAlbumIcon(mCursor, mPlayPosition);

        Intent intent = new Intent();
        intent.setAction(ACTION_UPDATE_INFO);
        intent.putExtra("info", info);
        intent.putExtra("title", title);
        intent.putExtra("albumArt", albumArt);
        sendBroadcast(intent);
    }

    //获取当前播放歌曲长度
    private void toUpdateDuration(){
        String duration = getDuration(mCursor, mPlayPosition);
        Intent intent = new Intent();
        intent.setAction(ACTION_UPDATE_DURATION);
        intent.putExtra(ACTION_UPDATE_DURATION, duration);
        sendBroadcast(intent);
    }

    //更新进度
    private void toUpdateProgress(){
        if(!flagStop && mMediaPlayer != null && mMediaPlayer.isPlaying()){
            int progress = mMediaPlayer.getCurrentPosition();

            Intent intent = new Intent();
            intent.setAction(ACTION_UPDATE_PROGRESS);
            intent.putExtra(ACTION_UPDATE_PROGRESS, progress);
            sendBroadcast(intent);
            handler.sendEmptyMessageDelayed(updateProgress, 1000);
        }else {
            flagPro = false;
        }
    }

    private Handler handler = new Handler(){

        public void handleMessage(Message msg){
            switch(msg.what){
                case updateProgress:
                    toUpdateProgress();
                    break;
                case updateDuration:
                    toUpdateDuration();
                    break;
                case updateInfo:
                    toUpdateInfo();
                    break;
                case updateList:
                    toUpdateList();
                    break;
                default:
                    break;
            }
        }
    };

    private int randPosition() {
        int random = (int)(Math.random() * (musicList.size() - 1));
        return random;
    }

    //服务结束时要释放MediaPlayer
    public void onDestroy() {
        super.onDestroy();
        System.out.println("MusicServer onDestroy");
        mMediaPlayer.release();
    }


}
